package com.scproject.utils;

import com.scproject.scbef.exception.ProcessException;
import com.scproject.scbef.mapper.ImgMapper;
import com.scproject.scbef.mapper.ImgRelationMapper;
import com.scproject.scbef.pojo.Img;
import com.scproject.scbef.pojo.ImgRelation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LNL
 * @date 2021/5/24 23:04
 */
@Slf4j
public class FtpFileUtil {
    //请求文件时的名称
    private static final String REQUEST_FILE_NAME = "file_transfer";

    //ftp服务器ip地址
    private static final String FTP_ADDRESS = "139.196.238.180";
    //端口号
    private static final int FTP_PORT = 21;
    //用户名
    private static final String FTP_USERNAME = "user_lnl";
    //密码
    private static final String FTP_PASSWORD = "123456789";
    //图片路径
    private static final String FTP_BASEPATH = "/home/htdocs/image_sources";

    //处理视频,返回视频地址
    public static String uploadVideo(MultipartHttpServletRequest request) {

        //返回一个路径+名字的集合
        boolean flag = false;
        String path = "";
        List<MultipartFile> files = request.getFiles(REQUEST_FILE_NAME);
        FTPClient ftpClient = new FTPClient();
        //1、测试连接
        if (connect(ftpClient)) {
            try {
                //检验工作目录是否存在
                if (ftpClient.changeWorkingDirectory(FTP_BASEPATH)) {
                    for (MultipartFile file : files) {
                        //原始文件名
                        String originalFilename = file.getOriginalFilename();
                        //文件后缀名
                        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                        //文件名
                        String fileName = UUIDUtils.getUUID() + suffix;
                        //检验是否上传成功
                        if (storeFile(ftpClient, fileName, file.getInputStream())) {
                            //返回一个路径出去
                            path = FTP_ADDRESS + FTP_BASEPATH + "/" + fileName;
                        }
                    }
                }
                disconnect(ftpClient);
            } catch (IOException e) {
                log.error("工作目录不存在");
                e.printStackTrace();
                disconnect(ftpClient);
            }
        }
        return path;
    }

    /**
     * @param request
     * @param relationId
     * @param imgMapper
     * @param imgRelationMapper
     * @param type
     * @return
     */
    public static boolean upload(MultipartHttpServletRequest request,
                                 String relationId,
                                 String type,
                                 ImgMapper imgMapper,
                                 ImgRelationMapper imgRelationMapper) {

        //返回一个路径+名字的集合
        boolean flag = false;
        List<MultipartFile> files = request.getFiles(REQUEST_FILE_NAME);
        FTPClient ftpClient = new FTPClient();
        //1、测试连接
        if (connect(ftpClient)) {
            try {
                //检验工作目录是否存在
                if (ftpClient.changeWorkingDirectory(FTP_BASEPATH)) {
                    for (MultipartFile file : files) {
                        //原始文件名
                        String originalFilename = file.getOriginalFilename();
                        //文件后缀名
                        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                        //文件名
                        String fileName = UUIDUtils.getUUID() + suffix;
                        //检验是否上传成功
                        if (storeFile(ftpClient, fileName, file.getInputStream())) {
                            //返回一个路径出去
                            String path = FTP_ADDRESS + FTP_BASEPATH + "/" + fileName;
                            //进行数据库操作
                            Img img = new Img();
                            img.setId(UUIDUtils.getUUID());
                            img.setPath(path);
                            img.setName(fileName);
                            int isInsertImg = imgMapper.insertSelective(img);

                            ImgRelation imgRelation = new ImgRelation();
                            imgRelation.setId(UUIDUtils.getUUID());
                            imgRelation.setImgId(img.getId());
                            imgRelation.setRelationId(relationId);
                            imgRelation.setType(type);
                            int isInsertImgRelation = imgRelationMapper.insertSelective(imgRelation);
                            if (isInsertImg > 0 && isInsertImgRelation > 0) {
                                flag = true;
                            }else {
                                throw new ProcessException("处理失败");
                            }

                        }
                    }
                }
                disconnect(ftpClient);
            } catch (IOException e) {
                log.error("工作目录不存在");
                e.printStackTrace();
                disconnect(ftpClient);
            }
        }
        return flag;
    }

    /**
     * @param ftpClient       ftp客户端
     * @param saveName        存储的名字
     * @param fileInputStream 文件流
     * @return
     */
    public static boolean storeFile(FTPClient ftpClient, String saveName, InputStream fileInputStream) {
        boolean flag = false;
        try {
            if (ftpClient.storeFile(saveName, fileInputStream)) {
                flag = true;
                log.info("上传成功");
                disconnect(ftpClient);
            }
        } catch (IOException e) {
            log.error("上传失败");
            disconnect(ftpClient);
            e.printStackTrace();
        }
        return flag;
    }


    /**
     * 连接ftp
     *
     * @param ftpClient
     * @return
     */
    public static boolean connect(FTPClient ftpClient) {
        boolean flag = false;
        try {
//            ftpClient.enterLocalPassiveMode();

            FTPClientConfig config = new FTPClientConfig();
            config.setLenientFutureDates(true);
            ftpClient.configure(config);

            ftpClient.connect(FTP_ADDRESS, FTP_PORT);
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.setControlEncoding("UTF-8");
            if (ftpClient.login(FTP_USERNAME, FTP_PASSWORD)) {
                log.info("连接ftp成功");
                flag = true;
            } else {
                log.error("连接ftp失败，可能用户名密码错误");
                try {
                    disconnect(ftpClient);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 关闭连接
     *
     * @param ftpClient
     */
    public static void disconnect(FTPClient ftpClient) {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
                log.error("已关闭连接");
            } catch (IOException e) {
                log.error("未关闭连接");
                e.printStackTrace();
            }
        }
    }

}
